<template>
  <div class="user-list-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>用户列表</span>
        <el-button type="primary" @click="handleAdd" class="add-btn">
          <i class="el-icon-plus"></i> 新增用户
        </el-button>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="search-filter">
        <el-input
          v-model="searchForm.username"
          placeholder="请输入用户名"
          clearable
          prefix-icon="el-icon-search"
          style="width: 200px; margin-right: 10px;"
        ></el-input>
        <el-select
          v-model="searchForm.status"
          placeholder="请选择状态"
          clearable
          style="width: 150px; margin-right: 10px;"
        >
          <el-option label="启用" :value="1"></el-option>
          <el-option label="禁用" :value="2"></el-option>
        </el-select>
        <el-select
          v-model="searchForm.role"
          placeholder="请选择角色"
          clearable
          style="width: 150px; margin-right: 10px;"
        >
          <el-option label="管理员" :value="'admin'"
            ></el-option
          >
          <el-option label="普通用户" :value="'user'"
            ></el-option
          >
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>

      <!-- 用户表格 -->
      <el-table v-loading="loading" :data="userListData" style="width: 100%;">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="avatar" label="头像" width="60">
          <template slot-scope="scope">
            <el-avatar style="width: 30px; height: 30px;" :src="scope.row.avatar ? $imgUrl + scope.row.avatar : defaultAvatar"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="account" label="账号" width="180"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="phone" label="电话" width="150"></el-table-column>
        <el-table-column prop="role" label="角色" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.role === 'admin'" type="primary">管理员</el-tag>
            <el-tag v-else>普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope" v-if="scope.row.account != userInfo.account">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button class="col-huan" type="text" @click="handleRestPwd(scope.row._id)">重置密码</el-button>
            <el-button class="col-hon" type="text" @click="handleDelete(scope.row._id,scope.row.username)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
        <UserAdd ref="userAdd" @initList="handleSearch" />
        <UserEdit ref="userEdit" @initList="handleSearch" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { getUsers as getUsersAPI,deleteUser,restPwd } from '@/api/users'
import UserAdd from './UserAdd.vue'
import UserEdit from './UserEdit.vue'
export default {
  name: 'UserList',
  components: {
    UserAdd,
    UserEdit
  },
  data () {
    return {
      searchForm: {
        username: '',
        status: '',
        role: ''
      },
      userList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      defaultAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      userInfo: '',
    }
  },
  computed: {
    userListData () {
      // 根据分页计算当前页的数据
      const startIndex = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const endIndex = startIndex + this.pagination.pageSize
      return this.userList.slice(startIndex, endIndex)
    }
  },
  mounted () {
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    this.getUsers()
  },
  methods: {
    getUsers () {
      this.loading = true
      const params = {
        ...this.searchForm,
        page: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      getUsersAPI(params).then(response => {
        this.userList = response.list || []
        this.userList.forEach(item => {
          item.createdAt = this.$dateBtn(item.createdAt)
          item.updatedAt = this.$dateBtn(item.updatedAt)
        })
        this.pagination.total = response.page.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取用户列表失败:', error)
        this.loading = false
        this.$message.error('获取用户列表失败，请稍后重试')
      })
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.getUsers()
    },
    handleReset () {
      this.searchForm = {
        username: '',
        status: '',
        role: ''
      }
      this.handleSearch()
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
    },
    handleAdd (row) {
      this.$refs.userAdd.openDialog(row);
      // this.$router.push('/user/add')
    },
    handleEdit (row) {
      this.$refs.userEdit.openDialog(row);
      // this.$router.push(`/user/edit/`)
    },
    handleDelete (id, username) {
      this.$confirm(`确定要删除用户 "${username}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        this.loading = true
        deleteUser({id: id}).then(res => {
          if (res.errCode == 0) {
            this.handleSearch()
            this.loading = false
            this.$message.success('删除成功')
          } else {
            this.$message.error(res.errMsg)
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleRestPwd (id) {
      this.$prompt('请输入密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^.{6,20}$/,
          inputErrorMessage: '密码格式不正确'
        }).then(({ value }) => {
          restPwd({id: id, password: value}).then(res => {
            if (res.errCode == 0) {
              this.handleSearch()
              this.loading = false
              this.$message.success('重置成功')
            } else {
              this.$message.error(res.errMsg)
            }
          })
          // this.$message({
          //   type: 'success',
          //   message: '你的密码是: ' + value
          // });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
    }
  }
}
</script>

<style lang="scss" scoped>
.user-list-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.el-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  text-align: left;
}

.add-btn {
  float: right;
}

.search-filter {
  margin: 15px 0;
  padding: 10px;
  background: #fafafa;
  border-radius: 6px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  flex: 1;
  overflow: auto;
}
</style>
